var 
	http = require('http'),
	urlutil = require('url'),
	path = require('path'),
	mime = require('./mime'),
	schedule = require("node-schedule"),//定时调度
	mongodb = require('mongodb'),
	ObjectID = require('mongodb').ObjectID,
	socketio = require('socket.io'),
	server = http.createServer(function (request, response) {
		response.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin':'node路径'});
	}).listen(888, function(){
		console.log('start listening....');	
	});
dbServer  = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
db = new mongodb.Db('mydb', dbServer, {safe:true});
String.prototype.trim=function(){
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
	
/*	usrStore设计思想：
 *	每个用户ID都是usrSotre的一个属性，这个属性对应用户打开每个的socket会话集合数组
 *	usrStore = {
	 '11144' : [socket1, socket2, socket3...],
	 '11122' : [socket1, socket2, socket3...] 
	}
*/
var	usrStore = {};
//通信监听函数。
socketio.listen(server).on('connection', function (socket) {	
	socket.on('message', function (msg) {
		socket.broadcast.emit('message', msg);
	});
	//用户会话进入
	socket.on('login', function(id, state) {
		usr = usrStore[id] || (usrStore[id] = []);
		socket.uid = id;
		socket.state = state;
		usr.push(socket)
	});
	
	//客户端获取日历内容请求
	socket.on('getCalendarContent', function(){
		manager.sendCalendarData(arguments[0], arguments[1]);
	});
	
	//客户端发送的当天计划请求
	socket.on('getDayPlan', function(uid, day){
		manager.sendDayPlan(uid, day)
	});
	//客户端提交用户修改记录
	socket.on("post", function(data){
		manager.updateDayPlan(data);
	});
	
	//页面关闭处理
	socket.on('disconnect', function(){
		manager.disConnectDel(socket)
	});
	
	//客户页面切换状态处理
	socket.on('pageState', function(state) {
		if('blur' == state) {
			socket.state = 'blur';	
		}
		else {
			socket.state = 'focus';
		}
	});
	//用户签收后，有可能存在多页面收到提醒信息，这里回发一个删除信息。
	socket.on('usrSigned', function(uid) {
		var curUsr = usrStore[uid] || [];
		for(var j = 0, len = curUsr.length; j <　len; j++) {
			curUsr[j].emit('cancelRemind', curData);	
		}
	});
});
function Manager() {
	this.monthMemory = {};
	this.dayPlanMemory = {};
	this.dayRepeatNote = {};	//每日重复记录
	this.daySchedule = {};
	this.dayWork = {};
	this.idCancelTime = {};
	this.dayIdInfo = {};
	this.noReaptIdArr = {}; //用来记录调度中用户指定的不循环计划。
	this.noPlanDay = []; 
}
Manager.prototype = {
	/*
	 *为了避免node挂了和方便调试，Node每次重启都需要根据当天的计划重新来添加当天调度。每天00:02都重新获取新一天的提醒计划。
	*/
	init : function() {
		var date = new Date(), curYear, curMonth, curDay,
			curHour = date.getHours(),
			curMinute = date.getMinutes(),
			yearMonthDay,
			dayIdInfo = manager.dayIdInfo = {};
			
		this.curDate = date;
		this.curYear = curYear = date.getFullYear(),
		this.curMonth = curMonth = date.getMonth() + 1,
		this.curDay = curDay = date.getDate(),
		yearMonthDay = curYear + '-' + curMonth + '-' + curDay;
		usrStore = {};
		db.open(function(err, db){
			if(err){
				console.log(err);
			}
			else {
				manager.getDaySchData(yearMonthDay, 'doSch');
			}
		});
	},
	/*
	 *函数说明：该函数用来获取某天的调度计划，包括当天和指定日期的
	 *@param {string} yearMonthDay 日期，格式：2014-8-13
	 *@param {boolean} doPlan 为true执行今天的调度，为false只是用这个函数获取某天的调度
	 *@param {string} uid 员工id
	 *@param {array} date 日期，格式[2014, 8, 13]
	*/
	getDaySchData : function (yearMonthDay, doPlan, uid, date){
		var dayIdInfo = this.dayIdInfo;
		db.createCollection('schedule', {safe:true}, function(err, collection){
			if(err){
				console.log(err);return;
			}else{
				collection.findOne({day:yearMonthDay}, function(err, result) {
					var 
						curData, time, finded, len,
						dayRepeatNote = manager.dayRepeatNote,
						daySchedule = manager.daySchedule, scheduleData;
					if(err) {
						console.log(err);
					}
					else {	
						if(null !== result && 0 != result.data.length){
							scheduleData = result.data;
							len = scheduleData.length;
							console.log(scheduleData);
							//manager.clearDaySch(yearMonthDay);return;
							for(var i = 0; i < len; i++) {
								curData = scheduleData[i];
								curDayIdInfo = dayIdInfo[curData.uid] || (dayIdInfo[curData.uid] = {});
								dayWrap = curDayIdInfo[yearMonthDay] || (curDayIdInfo[yearMonthDay] = {});
								idTag = dayWrap[curData.id] || (dayWrap[curData.id] = {});
								idTag.uid = curData.uid;
								idTag.time = idTag.time || [];
								idTag.time.push(curData.time);
								idTag.execute = idTag.execute || [];
								idTag.execute.push(curData.execute)
								idTag.cancel = idTag.cancel || [];	
								idTag.cancel.push(curData.cancel);
								idTag.changed = idTag.changed || [];
								idTag.changed.push(curData.change);
								idTag.added = idTag.add || 0;
								idTag.added++;
							}
						}
						else {
							manager.noPlanDay.push(yearMonthDay);
						}
						switch(doPlan) {
							case 'doSch':
								manager.doCurDayPlan(dayIdInfo);	
								break;
							case 'getDaySchOne' :
								manager.getRepeatNote(uid, date);
								break;
							case 'getDaySchTwo':
								curDayIdInfo = dayIdInfo[uid] || (dayIdInfo[uid] = {});
								dayWrap = curDayIdInfo[yearMonthDay] || (curDayIdInfo[yearMonthDay] = {});
								manager.sendCalendarData(uid, date);
								break;
						}
					}	
				});
			}
		});	
	},
	/*
	 *函数说明：执行当天计划的函数
	 *@param {object} dayIdInfo 当天要执行的计划对象
	*/
	doCurDayPlan : function(dayIdInfo) {
		var 
			curHour = this.curDate.getHours(),
			curMinute = this.curDate.getMinutes(),
			curYear = this.curYear,
			curMonth = this.curMonth,
			curDay = this.curDay,
			yearMonthDay = curYear + '-' + curMonth + '-' + curDay,
			dayWrap, idWrap, noReaptIdArr = this.noReaptIdArr;
			
		if(isEmptyObj(dayIdInfo)) return;
		db.createCollection('note', {safe:true}, function(err, collection){
			if(err) return;
			//根据ID取出该条数据的原始值
			for(uid in dayIdInfo) {
				dayWrap = dayIdInfo[uid];	
				idWrap = dayWrap[yearMonthDay];
				(function doScheduleDel(dayWrap, idWrap, uid){
					var len, dayIdWrapArr = [];
					for(id in idWrap) {
						dayIdWrapArr.push(id);	
					}
					len = dayIdWrapArr.length;
					_doCurDayPlan(0);
					function _doCurDayPlan(i){
						var sqnm = i;
						var id = dayIdWrapArr[i], idTag;
						collection.findOne({_id:ObjectID(id)}, function(err, result){
							if(err) {
								console.log(err)
								return;
							}
							if(null === result) return;
							var time = result.time.split(':'), nextDay, tempTime;
							if('' === result.repeatModel) {				//不循环
								if(time[0] > curHour || (time[0] == curHour && time[1] > curMinute)) {
									manager.doSchedule([curYear, curMonth, curDay], [time[0], time[1]], uid, id, false);   //未执行就只需执行
								}
								curUidNoReaptIdArr = noReaptIdArr[uid] || (noReaptIdArr[uid] = []);
								curUidNoReaptIdArr.push(result._id);
								if(++sqnm < len) {
									_doCurDayPlan(sqnm);
								}
								return;
							}
							//循环计划，计算出当天的循环
							idTag = idWrap[id];
							tempTime = idTag.time;
							tempCancel = idTag.cancel;
							tempExecute = idTag.execute;
							tempChanged = idTag.changed;
							timeLen = tempTime.length;
							
							idTag.time = [];
							idTag.cancel = [];
							idTag.execute = [];
							idTag.changed = [];
							
							firstTime = tempTime[0];
							tempHour = firstTime[0];
							tempMinite = firstTime[1];
							
							nextDay = {};
							switch(result.repeatModel) {
								case 0:
									leftRepeat = Math.floor((24 - tempHour) / result.repeatNum);
									for(var loop = 0; loop <= leftRepeat; loop++) {
										repeatHour = Number(tempHour) + Number(loop * result.repeatNum);
										if(repeatHour >= 24) break;
										idTagSqnm = '';
										for(timeLoop = 0; timeLoop < timeLen; timeLoop++) {
											if(repeatHour == tempTime[timeLoop][0] && tempMinite == tempTime[timeLoop][1]) {
												idTagSqnm = timeLoop;
												break;
											}	
										}
										curChange = false;
										curCancel = false;
										curExecute = false;
										if('' !== idTagSqnm) {
											curChange = tempChanged[idTagSqnm];
											curCancel = tempCancel[idTagSqnm];
											curExecute = tempExecute[idTagSqnm];
											if(true === curChange) break;
										}
										if(loop == leftRepeat) {
											tagHour = repeatHour + Number(result.repeatNum);
											tagDay = getNewDay(curYear+'-'+curMonth+'-'+curDay, Math.floor(tagHour/24));	
											tagHour = tagHour % 24;	
											nextDay = {
												day : tagDay,
												uid : uid,
												id : id,
												time : [tagHour, time[1]]	
											}
										}
										if(repeatHour < curHour || (repeatHour == curHour && time[1] < curMinute)) continue;
										idTag.time.push([repeatHour, tempMinite]);
										idTag.execute.push(curCancel);
										idTag.cancel.push(curCancel);
										idTag.changed.push(curChange);
										manager.doSchedule([curYear, curMonth, curDay], [repeatHour, time[1]], uid, id, nextDay); 
									}
									if(++sqnm < len) {
										_doCurDayPlan(sqnm);
									}
									return;
									break;
								case 1:
									tagDay = getNewDay(curYear+'-'+curMonth+'-'+curDay, result.repeatNum);
									break;
								case 2:
									tagDay = getNewDay(curYear+'-'+curMonth+'-'+curDay, result.repeatNum * 7);
								case 3:
									tagMonth = Number(curMonth) + Number(data.repeatNum);
									tagDay = [curYear, tagMonth, curDay];
									if(tagMonth > 12) {
										tagDay = [curYear + 1, tagMonth - 12, curDay];
									}
		
									break;	
							}
							nextDay = {
								day : tagDay,
								uid : uid,
								id : id,
								time : time[0] + ':' + time[1]	
							}
							//根据时间判断一下,若计划未执行，且时间已过，就为下一次执行添加。
							if(false === idTag.execute[0] && (time[0] < curHour || (time[0] == curHour && time[1] < curMinute))) {
								manager.updateExcute([curYear, curMonth, curDay], id, time, 'execute');
								manager.addSchedulePlan([curYear, curMonth, curDay], uid, id, time, {});
							}
							if(false == idTag.execute[0]  && (time[0] > curHour || (time[0] == curHour && time[1] >= curMinute))) {
								manager.doSchedule([curYear, curMonth, curDay], [time[0], time[1]], uid, id, nextDay); 	
							}
							if(++sqnm < len) {
								_doCurDayPlan(sqnm);
							}
						});
					}
				})(dayWrap, idWrap, uid);
			}
		});
	},
	/*
	*获取当月每一天第一条计划
	*@param {string} uid 用户id
	*@param {string} 当前用户查询年月
	*/
	sendCalendarData : function(uid, date){
		var 
			dayIdInfo = this.dayIdInfo,
			curDayIdInfo = dayIdInfo[uid] || (dayIdInfo[uid] = {}),
			dateTag, year, month, temp, maxDay, html, curMemory,
			yearMonth = date[0].toString() + date[1],
			day, yearMonth, usrSocket, hasPlan = [false];

		year = date[0];
		month = date[1];
		temp = new Date(year,month,0); //注：firefox下面是 new Date(2014/8/0)格式
		maxDay = temp.getDate();
		function _loopGetData(key) {
			var curKey = key,
			 	postDate = date, 
				ymd = year+'-'+month+'-'+curKey;
			if(undefined === curDayIdInfo[ymd]) {
				if(!inArray(manager.noPlanDay, ymd)) {
					manager.getDaySchData(ymd, 'getDaySchTwo', uid, date);
					return;	
				}
				else {
					curDayIdInfo[ymd] = {};
				}
			}
			
			if(isEmptyObj(curDayIdInfo[ymd])) {
				hasPlan.push(false);
			}
			else {
				hasPlan.push(true);	
			}
			if(++curKey <= maxDay){
				_loopGetData(curKey);	
			}
			else{
				yearMonth = postDate[0].toString() + postDate[1];
				month = month.toString();
				//该月第一天的星期：
				temp = new Date(year, (month-1), 1);
				firstWeekDay = temp.getDay(); 
				html = manager.createCalendarHtml(hasPlan, maxDay, firstWeekDay, year, month);
				usrSocket = manager.getCurUsrSocket(uid);
				if(isArray(usrSocket)) {
					for(var j = 0, len = usrSocket.length; j < len; j++) {
						usrSocket[j].emit('calendar-content', html);
					}
				}
				else {
					usrSocket.emit('calendar-content', html);	
				}

				html = '';
				if(!isEmptyObj(curDayIdInfo[date[0] + '-' + date[1] + '-' + date[2]]) && manager.curDay == date[2]) {
					manager.getRepeatNote(uid, postDate);
				}
				else {
					html = html + '<div class="no-plan">该日暂无计划</div><div class="add-calendar-wrap"><a class="add-note">添加计划</a><a class="upload-date-gray">保存更新</a></div><div class="calendar-input-wrap"><input type="text" class="calendar-input" /></div>';
					if(isArray(usrSocket)) {
						for(j = 0; j < len; j++) {
							usrSocket[j].emit('dayPlan-content', date, html, {}, -1);
						}
					}
					else {
						usrSocket.emit('dayPlan-content', date, html, {}, -1);	
					}
				} 
			}	

		}
		_loopGetData(1);
	},
	/*
	 *创建某月日历的Html内容
	 *@param {obj} curMemory, 该月每一天计划的集合，
	 *@param {string} maxDay, 该月的最大天数
	 *@param {string} firstWeekDay, 该月1号的星期
	 *@param {string} year, 当前年
	 *@param {string} month, 当前月
	*/
	createCalendarHtml : function(hasPlan, maxDay, firstWeekDay, year, month) {
		var maxLine = Math.ceil((maxDay + firstWeekDay) / 7),
			start = 1,
			date = new Date(),
			curYear = date.getFullYear(),
			curMonth = date.getMonth() + 1,
			curDay = date.getDate(),
			html = '<li class="per-line first-per-line"><ul class="week-name"><li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li></ul></li>';	
			
		for(var i = 0; i < maxLine; i++) {
			html = html + '<li class="per-line"><ul>';
			for(j = 0; j < 7; j++) {
				if(0 == j) {
					if(0 == i && j < firstWeekDay) {	//第一行，找出空的
						html = html + '<li class="left-li">&nbsp;</li>'
					}
					else {
						if(!hasPlan[start]) {
							if(year == curYear && month == curMonth && start == curDay) { 
								html = html + '<li class="cur-day left-li"><a>'+(start++)+'</a></li>';	
							}
							else {
								html = html + '<li class="left-li"><a>'+(start++)+'</a></li>';	
							}
						}	
						else {
							if(year == curYear && month == curMonth && start == curDay) {
								html = html + '<li class="cur-day left-li"><a class="has-tip">'+(start++)+'</a></li>';	
							}
							else {
								html = html + '<li class="left-li"><a class="has-tip">'+(start++)+'</a></li>';		
							}
						}
					}	
					if(start > maxDay) break;
					continue;	
				}
				if(0 == i && j < firstWeekDay) {	//第一行，找出空的
					html = html + '<li>&nbsp;</li>'
				}
				else {
					if(!hasPlan[start]) {
						if(year == curYear && month == curMonth && start == curDay) { 
							html = html + '<li class="cur-day"><a>'+(start++)+'</a></li>';	
						}
						else {
							html = html + '<li><a>'+(start++)+'</a></li>';	
						}
					}	
					else {
						if(year == curYear && month == curMonth && start == curDay) {
							html = html + '<li class="cur-day"><a class="has-tip">'+(start++)+'</a></li>';	
						}
						else {
							html = html + '<li><a class="has-tip">'+(start++)+'</a></li>';		
						}
					}
				}	
				if(start > maxDay) break;
			}
			html = html + '</ul></li>';
		}
		return html;
	},
	/*
	 *用户退出后根据socket.id属性从usrStore中删除
	 *@param {object} socket, 用户退出的链接，根据UID删除该用户的该会话。
	*/
	disConnectDel : function(socket){
		var i, j ,curUsr, uid;
		uid = socket.uid;
		curUsr = usrStore[uid] || [];
		for(j = 0, len = curUsr.length; j <　len; j++) {
			if(socket.id == curUsr[j].id) {
				console.log('删除了：'+j);
				curUsr.splice(j, 1);
				return;	
			}	
		}	
	},
	/*
	 *根据用户当前socket的状态来确定给哪个用户分发消息。
	 *@param {string} uid, 用户id
	 *注：focus也有可能存在多个，返回最后一个
	*/
	getCurUsrSocket : function(uid) {
		var i, j, curUsr, lastFocus = '';
		curUsr = usrStore[uid] || [];
		for(j = 0, len = curUsr.length; j <　len; j++) {
			if('focus' == curUsr[j].state) {
				lastFocus = j;	
			}	
		}
		if('' !== lastFocus) {
			return curUsr[lastFocus];	
		}
		return usrStore[uid];	
	},
	/*
	 *获取用户某天的工作计划
	 *@param {string} uid, 用户ID
	 *@param {string} day, 某天日期，格式：201474
	*/
	getDayPlan : function(uid, date) {
		var that = this, tempData, dayPlanMemory,
			day = date[0].toString() + date[1] + date[2];
			
		db.createCollection('note', {safe:true}, function(err, collection){
			key = uid+'-'+day;
			collection.find({key: key}).toArray(function(err, docs){
				var curMemory = that.monthMemory[uid] || (that.monthMemory[uid] = {}),
					dayPlan = curMemory[date[0].toString()+date[1]] || (curMemory[date[0].toString()+date[1]] = {});
				if(err) return;
				dayPlan[date[2]] = docs;
				that.getRepeatNote(uid, date);
			});	
		});
	},
	/*
	 *函数说明：根据用户UID将用户的当天循环提醒加入到当天的计划中
	 *@param {string} uid, 用户ID
	 *@param {array} date, 日期 格式：[2014, 8, 13]
	 *注：只记录当天的循环记录
	*/
	getRepeatNote : function(uid, date) {
		var 
			dayIdInfo = this.dayIdInfo,
			idArr = [], len, i, dataCollection = [],
			yearMonthDay = date[0]+'-'+date[1]+'-'+date[2],
			dayWrap = dayIdInfo[uid] || (dayIdInfo[uid] = {}),
			curDayIdInfo = dayWrap[yearMonthDay] || (dayWrap[yearMonthDay] = {});

		for(i in curDayIdInfo) {
			idArr.push(i)
		}			
		len = idArr.length;
		if(0 == len){
			this.sendDayPlan(uid, date, dataCollection);
			return;
		}

		db.createCollection('note', {safe:true}, function(err, collection){
			function _loopGetData(i){
				var id = idArr[i],
					idDayInfo = curDayIdInfo[id],
					timeArr = idDayInfo.time,
					cancelArr = idDayInfo.cancel,
					executeArr = idDayInfo.execute,
					changedArr = idDayInfo.changed;
				//console.log(idDayInfo)
				collection.findOne({_id: ObjectID(id)}, function(err,docs){
					var tempObj, loop, key, lenA;
					if(err) return;
					//idDayInfo无论是新增还是init执行都已经获取了循环，这里就是单纯的取数据。
					for(loop = 0, lenA = timeArr.length; loop < lenA; loop++) {
						if(changedArr[loop]) break;
						tempObj = {};
						for(key in docs) {
							tempObj[key] = docs[key];	
						}	
						tempObj.time = timeArr[loop][0]+':'+timeArr[loop][1];
						tempObj.execute = executeArr[loop] || false;
						tempObj.cancel = cancelArr[loop] || false;
						tempObj.changed = changedArr[loop] || false;
						dataCollection.push(tempObj);		
					}
					if(++i == len) {
						manager.sendDayPlan(uid, date, dataCollection);
					}	
					else{
						_loopGetData(i)	
					}
				});
			}
			_loopGetData(0);
		});
		return '';
	},
	/*
	 *将取到的当天计划信息发给客户端
	 *@param {string} uid, 用户ID
	 *@param {array} date， 某天的日期，格式：[2014, 7, 2]
	 *@param {array} repeatNote, 当天的调度计划.
	*/ 
	sendDayPlan : function(uid, date, repeatNote) {
		var plan = this.dayPlanMemory[uid] || {}, 
			tempI, dayPlan, i, len, lenA, curPlan, 
			html = '', usrSocket, dayRepeatNote, hasPlan = false,
			basicHTML, noNoteDiv,  defaultNoteData = {}, noteKey = 0,
			noReaptIdArr = this.noReaptIdArr[uid] || [],
			ymd = date[0] + '-' + date[1] + '-' + date[2],
			dayIdInfo = this.dayIdInfo,
			curDayIdInfo = dayIdInfo[uid] || (dayIdInfo[uid] = {}),
			dayWrap = curDayIdInfo[ymd] || (curDayIdInfo[ymd] = {});

		if(!isEmptyObj(dayWrap) && undefined === repeatNote){
			manager.getRepeatNote(uid, date);
			return;	
		}	
		
		if(isEmptyObj(dayWrap) && undefined === repeatNote) {	//注：凡是能够做这个请求的都表示当天有数据.
			manager.getDaySchData(ymd, 'getDaySchOne', uid, date);
			return;
		} 
		basicHTML = '<div class="add-calendar-wrap"><a class="add-note">添加计划</a><a class="upload-date-gray">保存更新</a></div><div class="calendar-input-wrap"><input type="text" class="calendar-input" /></div>';
		noNoteHTML = '<div class="no-plan">该日暂无计划</div>';
		len = repeatNote.length;
		if(0 != len) {
			for(i = 0; i < len; i++) {
				if(null === repeatNote[i] || undefined === repeatNote[i]) continue;
				curPlan = repeatNote[i];
				if('' === curPlan.repeatModel || inArray(noReaptIdArr, curPlan._id.toString())){
					curPlan.type = 'nopeat';
					html = html + '<div class="per-calendar" data="'+noteKey+'"><i class="time-wrap">'+curPlan.time+'</i><span class="content-wrap">'+curPlan.plan+'</span><a class="log-config"></a></div>';
				}
				else {
					curPlan.type = 'repeat';
					if(curPlan.cancel) {
						html = html + '<div class="per-calendar plan-cancel" data="'+noteKey+'"><i class="time-wrap time-repeat">'+curPlan.time+'</i><span class="content-wrap">'+curPlan.plan+'</span><a class="log-config"></a><span class="cancel-pic"></span></div>';
					}
					else {
						html = html + '<div class="per-calendar" data="'+noteKey+'"><i class="time-wrap time-repeat">'+curPlan.time+'</i><span class="content-wrap">'+curPlan.plan+'</span><a class="log-config"></a></div>';
					}
				}
				defaultNoteData[noteKey++] = curPlan;
			}
		}
		_sendDayPlan(html);
		function _sendDayPlan(html){
			if('' == html) {
				html = noNoteHTML + basicHTML;
			}
			else {
				html = html + basicHTML;	
			}
			usrSocket = manager.getCurUsrSocket(uid);
			if(isArray(usrSocket)) {
				for(i = 0, len = usrSocket.length; i < len; i++) {
					usrSocket[i].emit('dayPlan-content', date, html, defaultNoteData, noteKey);
				}
			}
			else {
				usrSocket.emit('dayPlan-content', date, html, defaultNoteData, noteKey);	
			}	
		}
	},
	/*
	 *函数说明：工作计划更新函数，包括新增，删除，修改
	 *@param {object} data 用户传过来的修改计划的数据
	*/
	updateDayPlan : function(data){
		var uid = data.uid,
			day = data.day,
			ymd = data.ymd,
			added = data.added,
			curDay = data.yearMonthDay[0] + '-' + data.yearMonthDay[1] + '-' + data.yearMonthDay[2],
			addNum = data.addStartNum,
			changed = data.changed,
			removed = data.removed,
			yearMonthDay = data.yearMonthDay,
			i, addedLen, removedLen, curAdd, curData, idTag, dataArr = [],
			usrDayWork = manager.dayWork[uid] || {},
			dayIdInfo = this.dayIdInfo,
			noReaptIdArr =  this.noReaptIdArr[uid] || (this.noReaptIdArr[uid] = []),
			curDayIdInfo = dayIdInfo[uid] || (dayIdInfo[uid] = {}),
			dayWrap = curDayIdInfo[curDay] || (curDayIdInfo[curDay] = {});
			
		removedLen = removed.length;
		addedLen = added.length;
		//删除
		if(0 != removedLen) {
			_removeDel(removedLen, removed);
		}
		if(!isEmptyObj(changed)) {					//更新
			db.createCollection('note', {safe:true}, function(err, collection){
				var usrDayWork = manager.dayWork[uid] || {}, id;
				if(err){
					console.log(err);
					return;
				}
				for(i in changed) {
					curChanged = changed[i];
					changObj = {};
					needChange = true;
					for(j in curChanged) {
						switch(j) {
							case 'id': 
							case 'key':
							case 'defaultData':
								break;	
							case 'cancel':
								needChange = false;
								_curDayWorkCancel(curChanged, uid, yearMonthDay)
								break;
							case 'repeatNum':
							case 'repeatModel':
							case 'time':
								needChange = false;
								_curRepeatChange(curChanged, uid, yearMonthDay, day);
								break;
							default:
								changObj[j] = curChanged[j];
								break	
						}
						if(!needChange) break;
					}	
					if(!needChange) continue;
					collection.update({_id:ObjectID(curChanged.id)}, {$set:changObj}, {safe:true}, function(err, result){
						if(err) {
							console.log(err)	
						}
						else {
							console.log(result);
						}
					});
				}
			});
		}
		//新增
		if(0 != addedLen) { 
			_addPlan(added);
		}
		/*
		 *函数说明：新增计划处理。
		*/
		function _addPlan(added){
			var addedLen = added.length, idTag, returnArr, dataArr = [], returnDay;
			for(var i = 0; i < addedLen; i++) {
				curAdd = added[i];
				dataArr.push({
					key : uid+'-'+day,
					time : curAdd.time,
					day : yearMonthDay,
					plan : curAdd.plan,
					repeatModel : curAdd.repeatModel,
					repeatNum : curAdd.repeatNum,
					remindWay : 'oa',
					note : ''
				})
			}
			db.createCollection('note', {safe:true}, function(err, collection){
				var usrDayWork = manager.dayWork[uid] || {}, id, tagHour, execute;
				if(err){
					console.log(err);
					return;
				}
				collection.insert(dataArr, {safe:true}, function(err,result){		
					var curResult, returnArr, day, hour, nextDay = {},
						curYear = manager.curYear,
						curMonth = manager.curMonth,
						curDay = manager.curDay,
						ymd;				
					if(err) {
						console.log(err);
						return;  
					}
					for(var i = 0, len = result.length; i < len; i++) {
						curResult = result[i];
						id = curResult._id;
						curResult.uid = uid;
						//如果是今天之前添加的，就为其添加一条记录.
						if(Number(yearMonthDay[0]) + Number(yearMonthDay[1]) + Number(yearMonthDay[2]) <　(curYear + curMonth + curDay)) {
							ymd = yearMonthDay[0] + '-' + yearMonthDay[1] + '-' + yearMonthDay[2]
							manager.addSchedulePlan(yearMonthDay, uid, id, curResult.time.split(':'), {execute:true});
							dayWrap = curDayIdInfo[ymd] || (curDayIdInfo[ymd] = {});
							idTag = dayWrap[id] = {};
							idTag.uid = uid;
							idTag.time = idTag.time || [];
							idTag.time.push(curResult.time.split(':'))
							idTag.execute = idTag.execute || [];
							idTag.execute.push(true);
							idTag.cancel = idTag.cancel || [];	
							idTag.cancel.push(false);
							idTag.changed = idTag.changed || [];
							idTag.changed.push(false);
							idTag.added = idTag.add || 0;
							if('' === curResult.repeatModel) {
								manager.noReaptIdArr[uid].push(id);
							}
						}
						returnArr = manager.getFirstTime(yearMonthDay, curResult);
						returnDay = returnArr[0];
						time = returnArr[1].split(':');
						console.log('返回的时间数据');
						console.log('日期：'+ returnDay);
						console.log('时间：'+time);
						//在今天执行，
						if(returnDay[0] == curYear && returnDay[1] == curMonth && returnDay[2] == curDay) {
							ymd = curYear + '-' + curMonth + '-' + curDay
							dayWrap = curDayIdInfo[ymd] || (curDayIdInfo[ymd] = {})
							idTag = dayWrap[id] = {};
							idTag.uid = uid;
							idTag.time = idTag.time || [];
							idTag.execute = idTag.execute || [];
							idTag.cancel = idTag.cancel || [];	
							idTag.changed = idTag.changed || [];
							idTag.added = idTag.add || 0;
							switch(curResult.repeatModel) {
								case 0:
									leftRepeat = Math.floor((24 - time[0]) / curResult.repeatNum);
									for(var sqnm = 0; sqnm <= leftRepeat; sqnm++) {
										loopHour = Number(time[0]) + Number(sqnm * curResult.repeatNum);
										if(tagHour >= 24) break;
										idTag.time.push([loopHour, time[1]]);
										idTag.execute.push(false);
										idTag.cancel.push(false);
										idTag.changed.push(false);
										idTag.added++;
										if(sqnm == leftRepeat) {
											tagHour = Number(time[0]) + (sqnm + 1)* curResult.repeatNum;
											tagDay = getNewDay(returnDay[0]+'-'+returnDay[1]+'-'+returnDay[2], Math.floor(tagHour/24));	
											tagHour = tagHour % 24;
											nextDay = {
												day : tagDay,
												uid : uid,
												id : id,
												time : tagHour + ':' + time[1]	
											}
										}
										manager.doSchedule(returnDay, [loopHour, time[1]], uid, id, nextDay); 											
									}
									manager.addSchedulePlan(returnDay, uid, id, time, {execute:false});
									manager.sendDayPlan(uid, yearMonthDay);
									return;
									break;
								case 1:
									tagDay = getNewDay(returnDay[0]+'-'+returnDay[1]+'-'+returnDay[2], curResult.repeatNum);
									break;
								case 2:
									tagDay = getNewDay(returnDay[0]+'-'+returnDay[1]+'-'+returnDay[2], curResult.repeatNum * 7);
								case 3:
									tagMonth = Number(day[1]) + data.repeatNum;
									tagDay = [returnDay[0], tagMonth, returnDay[2]];
									if(tagMonth > 12) {
										tagDay = [Number(returnDay[0]) + 1, Number(tagMonth) - 12, returnDay[2]];
									}
									break;	
								default:
									hour = manager.curDate.getHours();
									minute = manager.curDate.getMinutes();
									manager.noReaptIdArr[uid].push(id);
									if(time[0] > hour || (time[0] == hour && minute <= time[1])) {
										manager.doSchedule(returnDay, time, uid, id, nextDay); 
										idTag.execute.push(false);
									}
									else {
										idTag.execute.push(true);
										manager.addSchedulePlan(returnDay, uid, id, time, {execute:true});	
									}
									idTag.time.push(time);
									idTag.cancel.push(false);
									idTag.changed.push(false);
									idTag.added++;
									manager.sendDayPlan(uid, yearMonthDay);
									return;
									break;
							}
							nextDay = {
								day : tagDay,
								uid : uid,
								id : id,
								time : time	
							}
							manager.doSchedule(returnDay, time, uid, id, nextDay);
						}
						else {	//循环在将来，就为将来的日期添加第一次调度，并在制定计划的当天添加该次执行。
							manager.addSchedulePlan(returnDay, uid, id, time, {execute:false}); //为将来添加调度
							idTag = dayWrap[id] = {};
							idTag.uid = uid;
							idTag.time = idTag.time || [];
							idTag.time.push(curResult.time.split(':'))
							idTag.execute = idTag.execute || [];
							idTag.execute.push(false);
							idTag.cancel = idTag.cancel || [];	
							idTag.cancel.push(false);
							idTag.changed = idTag.changed || [];
							idTag.changed.push(false);
						}
					}
					//更新完毕后重新退回给客户端，保证两边的数据是最新的。
					manager.sendDayPlan(uid, yearMonthDay);
				}); 
			});	
		}
		/*
		 *函数说明：删除某条计划提醒
		 *@param {string} removedLen 要删除的个数
		 *@param {array} removed 要删除计划的id的集合
		*/
		function _removeDel(removedLen, removed) {
			var curWork, id, idArr = [];
			for(var i = 0; i < removedLen; i++) {
				id = removed[i];
				//1,取消当前的调度
				curWork = usrDayWork[id];
				for(key in curWork) {
					curWork[key].cancel();	
				}
				idArr.push(id);
				//2，删除dayWrap
				delete dayWrap[id];
			}
			manager.getRepeatNote(uid, yearMonthDay);
			//3,更新schedule表数据.
			db.createCollection('schedule', {safe:true}, function(err, collection){
				var key = yearMonthDay[0]+'-'+yearMonthDay[1]+'-'+yearMonthDay[2];
				if(err){
					console.log(err);
				}else{
					collection.findOne({day:key}, function(err, result) {
						var newData = [], scheduleData;
						if(err) {
							console.log(err)
							return;
						}
						if(null === result) return;
						scheduleData = result.data;
						len = scheduleData.length;
						if(0 == len) return;
						for(var i = 0; i < len; i++) {
							curData = scheduleData[i];	
							if(!inArray(idArr, curData.id)) {
								newData.push(curData);	
							}
						}
						collection.update({day:key},{$set:{data:newData}},{safe:true}, function(err, result){
							if(err) {
								console.log(err)	
							}
							else {
								console.log('删除数据，schedule表数据更新成功!');
							}
						});
					});
				}
			});
		}
		/*
		 *函数说明：计划时间，循环方式，循环周期变更处理
		 *@param {obj} data 客户端传过来的数据
		 *@param {string} uid 用户工号
		 *@param {array} day 格式：[2014, 8, 13]
		 *说明：这几项的修改都可以视为先将之前的提醒删除，然后根据新条件重新生成计划。 
		*/
		function _curRepeatChange(data, uid, day, date) {
			var 
				defaultData =  data.defaultData,
				id = defaultData._id,
				idTag = dayWrap[id],
				time = defaultData.time,
				tempTime = time.split(':'),
				usrDayWork = manager.dayWork[uid] || {}, 
				curWork = usrDayWork[id],
				key, len, curTime, timeArr = [], addData, sqnm, repeatModel;
			//1, 找出修改前的调度计划.
			for(key in curWork) {
				curTime = key.split('-');
				if(curTime[0] > tempTime[0] || (curTime[0] == tempTime[0] && curTime[1] >= tempTime[1])) {
					curWork[key].cancel();	
					console.log('change cancel了')
				}	
			}
			//2, 修改dayWrap，将旧的数据更新
			timeArr = idTag.time;
			for(key = 0, len = timeArr.length; key < len; key++) {
				curTime = timeArr[key];
				if(curTime[0] == tempTime[0] && curTime[1] == tempTime[1]) {
					sqnm = key;
					break;	
				}	
			}
			idTag.changed[sqnm] = true;
			//3,为该记录生成已取消的调度计划
			manager.addSchedulePlan(day, uid, id, tempTime, {change:true});
			//4，生成该日的新计划，后续的数据以修改后数据优先，若没有就直接用defaultData里面的数据
			if(undefined === data.repeatModel) {
				repeatModel = defaultData.repeatModel;
			}
			else {
				repeatModel = data.repeatModel;
			}
			addData = [{
				key : uid+'-'+date,
				time : time,
				day : day,
				plan : data.plan || defaultData.plan,
				repeatModel : repeatModel,
				repeatNum : data.repeatNum || defaultData.repeatNum,
				remindWay : 'oa',
				note : ''	
			}];
			_addPlan(addData);
		}
		function _curDayWorkCancel(data, uid, day){
			var 
				id = data.id,
				time = data.time.split(':'),
				idTag = dayWrap[id],
				idWork = usrDayWork[id],
				tagKey = time[0] + '-' + time[1],
				timeArr = idTag.time,
				tempKey, len, sqnm;
				
			for(tempKey in idWork) {
				if(tempKey == tagKey) {
					idWork[tempKey].cancel();
					console.log('取消成功');
					//修改cancel标志	
					for(sqnm = 0, len = timeArr.length; sqnm < len; sqnm++) {
						curTime = timeArr[sqnm];
						if(curTime[0] == time[0] && curTime[1] == time[1]) {
							idTag.cancel[sqnm] = true;
							break;	
						}	
					}
					//为此次取消添加一个调度，但cancel为true;
					if(0 === sqnm) {
						manager.updateExcute(day, id, time, 'cancel');
					}
					else {
						manager.addSchedulePlan(day, uid, id, time, {cancel:true});
					}
					manager.getRepeatNote(uid, day);//重新生成计划列表
					return;
				}	
			}
		}
	},
	/*
	 *函数说明：根据新增来添加定时调度返回从添加时间开始的下一次执行时间。
	 *@param {array} postDay, 用户操作的日历日期
	 *@param {obj} date, 该条计划的内容
	*/
	getFirstTime : function(postDate, data) {
		var date = new Date(),
			curDay = date.getDate(),
			curYear = date.getFullYear(),
			curMonth = date.getMonth() + 1,
			
			postDay = Number(postDate[2]),
			postYear = 	Number(postDate[0]),
			postMonth = Number(postDate[1]),
			
			totalPost = postYear + postMonth + postDay,
			totalCur = curYear + curMonth + curDay,
			postTime = data.time.split(":");
			postHour = postTime[0],
			postMinute = postTime[1],
			curHour = date.getHours(),
			curMinute = date.getMinutes();
			
		tagDay = [postYear, postMonth, postDay];
		tagHour = postHour;
		//hour, day, week, month的循环都先计算出下一次的日期，然后当天执行的时候再将下一次执行的天数补充上去。
		//如果循环先将下一次执行的时间计算出来添加进去
		switch(data.repeatModel) {
			case 0:			//hour
				/*先判断时间，以当前时间为分界点。
				 *如果小于当前时间这需要计算根据重复的小时数计算下一次执行的时间；
				 *反之，若计划时间大于现在时间就直接将该提示时间插入到相应的日期提示中
				*/
				if((curYear+curMonth+curDay > postYear+postMonth+postDay) || 
				   (curYear+curMonth+curDay == postYear+postMonth+postDay && 
					(curHour > postHour || (curHour == postHour && curMinute >= postMinute))
				)){
					//根据循环计算出下一次执行的时间，以小时为准，不带入分钟	
					difTime = hourDiff(
						postYear+'/'+postMonth+'/'+postDay+" "+postHour+':00',
						curYear+'/'+curMonth+'/'+curDay+' '+curHour+':00'
					);
					leftHour = difTime%data.repeatNum;
					//如果整除说明当前小时数整好是循环小时，直接按当前小时，postMinute添加当天循环计划
					if(0 === leftHour && curMinute == postMinute) {
						//return [tagDay, postHour];
/*						this.addSchedulePlan([curYear, curMonth, curDay], data, curHour, postMinute);
						this.doSchedule([curYear, curMonth, curDay], [curHour, postMinute], data.uid, data._id);*/
					}
					else {
						if(0 == leftHour && curMinute >= postMinute) {
							tagHour = Number(curHour) + Number(data.repeatNum);	
						}
						else {
						 //  tagHour = Number(Math.ceil(difTime/data.repeatNum) * data.repeatNum  - difTime) + Number(curHour);
						   tagHour = Number(postHour) + Number(Math.ceil(difTime/data.repeatNum) * data.repeatNum);
						}
						if(tagHour >= 24) {
							tagDay = getNewDay(postYear+'-'+postMonth+'-'+postDay, Math.floor(tagHour/24));	
							tagHour = tagHour % 24;
						}
					}
				}
				break;
			case 1:			//day
				 //在制定计划之前计算下一次的时间，并添加计划。
				if((curYear+curMonth+curDay > postYear+postMonth+postDay) || 
				   (curYear+curMonth+curDay == postYear+postMonth+postDay && 
					(curHour > postHour || (curHour == postHour && curMinute > postMinute))
				)){
					tagDay = getNewDay(curYear+'-'+curMonth+'-'+curDay, data.repeatNum);	
				}
				break;
			case 2:				//week
				 //在制定计划之前就计算下一次的时间，并添加计划。
				if((curYear+curMonth+curDay > postYear+postMonth+postDay) || 
				   (curYear+curMonth+curDay == postYear+postMonth+postDay && 
					(curHour > postHour || (curHour == postHour && curMinute > postMinute))
				)){
					tagDay = getNewDay(curYear+'-'+curMonth+'-'+curDay, data.repeatNum * 7);	
				}
				break;
			case 3:			//month
				if((curYear+curMonth+curDay > postYear+postMonth+postDay) || 
				   (curYear+curMonth+curDay == postYear+postMonth+postDay && 
					(curHour > postHour || (curHour == postHour && curMinute > postMinute))
				)){
					tagMonth = curMonth + data.repeatNum;
					tagDay = [curYear, tagMonth, curDay];
					if(tagMonth > 12) {
						tagDay = [curYear + 1, tagMonth - 12, curDay];
					}
				}
				break;
			default:
				break;
		}
		return [tagDay, tagHour+':'+postMinute];	
	},
	/*
	 *新增调度计划表数据
	 *@param {array} tagDay， 0为年 1为月 2为天
	 *@param {obj} data 该计划的数据
	 *@param {string} key， 该记录在note表的主键
	 *@param {string} postHour 记录提醒的小时
	 *@param {string} postMinute 记录提醒的分钟
	*/
	addSchedulePlan	: function(tagDay, uid, id, time, options) {
		var	dataObj, execute = execute || false,
			curDay = tempKey = tagDay[0]+'-'+tagDay[1]+'-'+tagDay[2],
			options = options || {};
		console.log('-------添加调度表数据---------')
		console.log('人员工号：' + uid);
		console.log('日期：'+tagDay);
		console.log('具体时间：'+time);
		console.log('----------结束------------')
		db.createCollection('schedule', {safe:true}, function(err, collection){
			if(err){
				console.log(err);
			}else{
				collection.findOne({day:curDay}, function(err, docs){
					if(err){
						console.log(err);
						return;	
					}
					if(null === docs) {		//该天没有提醒数据
						dataObj = {
							day : curDay,
							data : 	[{
								id      : id,
								uid     : uid,
								time    : time,
								cancel  : options.cancel || false,
								change  : options.change || false, 	
								execute : options.execute || false
							}]
						}
						collection.insert(dataObj,{safe:true},function(err,result){
							if(err) {
								console.log('当天第一次新增调度日志出错！');
								return;	
							}
					   		console.log('当天调度第一次插入成功！');
						}); 
					}
					else {						//已有数据
						dataObj = {
							id      : id,
							uid     : uid,
							time    : time,
							cancel  : options.cancel || false,
							change  : options.change || false,
							execute : options.execute || false 	
						}
						docs.data.push(dataObj)
						collection.update({day:curDay}, {$set:{data: docs.data}}, {safe:true}, function(err, result){
							if(err) {
								console.log(err)	
							}
							else {
								console.log('schedule表更新成功!');
							}
						});
					}	
				})
			}
		});
	},
	/*
	 *立即执行调度
	 *@param {array} day, 0为年， 1为月， 2为日
	 *@param {array} time, 0为小时， 1为分钟
	 *@param {string} key, 该条记录在note表的记录key
	*/
	doSchedule : function(day, time, uid, id, nextDayObj) {
		var date = new Date(day[0], day[1]-1, day[2], time[0], time[1],0),
			work, perIdWork = [],
			dayWork = this.dayWork, 
			usrDayWork = dayWork[uid] || (dayWork[uid] = {}),
			idWork = usrDayWork[id] || (usrDayWork[id] = {}),
			nextDayObj = nextDayObj;

		console.log('------work-make-start--------');
		console.log('day:'+ day);
		console.log('uid:'+ uid);
		console.log('id:'+ id);
		console.log('time:'+ time);
		console.log('------work-make-end--------');
		idWork[time[0]+'-'+time[1]] = work = schedule.scheduleJob(date, function(defaultData){
			var i, j;
			db.createCollection('note', {safe:true}, function(err, collection){
				if(err){
					console.log('执行调度第一个err:'+err);
				}
				else{
					collection.findOne({_id:ObjectID(id)}, function(err, docs){
						var tempData, date, usrSocket, len,
							added = '', tempTime, curTime,
							dayIdInfo = manager.dayIdInfo,
							curDayIdInfo = dayIdInfo[uid] || (dayIdInfo[uid] = {}),
							dayWrap = curDayIdInfo[day[0]+'-'+day[1]+'-'+day[2]] || (curDayIdInfo[day[0]+'-'+day[1]+'-'+day[2]] = {});
							idTag = dayWrap[id] || (dayWrap[id] = {});
						if(err){
							console.log('执行调度第二个err:'+err);
							return;	
						}
						if(null === docs) return;
						curData = docs;
						usrSocket = manager.getCurUsrSocket(uid);
						curData.time = time[0] + ':' + time[1];
						if(isArray(usrSocket)) {
							for(i = 0, len = usrSocket.length; i < len; i++) {
								usrSocket[i].emit('planMessage', curData);
							}
						}
						else if(!isEmptyObj(usrSocket)){
							usrSocket.emit('planMessage', curData);	
						}
						//为此次执行的调度添加schedule记录
						console.log('-----------调度执行后添加该次调度的记录，数据如下：-------------')
						console.log('day:'+ day);
						console.log('uid:'+ uid);
						console.log('id:'+ id);
						console.log('time:'+ time);
						console.log('------------数据显示完毕---------')
						timeArr = idTag.time;
						for(var i = 0, len = timeArr.length; i < len; i++) {
							curTime = timeArr[i];
							if(time[0] == curTime[0] && time[1] == curTime[1]) {
								idTag.execute[i] = true;
								added = i;	
								break;
							}	
						}
						if(0 === added){
							manager.updateExcute(day, id, timeArr[added], 'execute')
						}
						else {
							manager.addSchedulePlan(day, uid, id, time, {execute:true});
						}
						if(!isEmptyObj(nextDayObj)) {
							manager.addSchedulePlan(nextDayObj.day, nextDayObj.uid, nextDayObj.id, nextDayObj.time, {execute:false});	
						}
					});
				}
			});
		});
	},
	//将schedule表中的该数据的execute标志修改为true
	updateExcute : function(day, id, time, key) {
		console.log('------------更新schedule表字段信息：-------------');
		console.log('day:' + day);
		console.log('id:' + id);
		console.log('time:' + time);
		console.log('key:' + key)
		db.createCollection('schedule', {safe:true}, function(err, collection){
			if(err){
				console.log('执行调度第三个err:'+err);
			}else{
				collection.findOne({day:day[0]+'-'+day[1]+'-'+day[2]}, function(err, result){
					if(err) return;
					if(null === result) return;
					var changeData = result.data;
					for(var i = 0, len = changeData.length; i < len; i++) {
						if(id == changeData[i].id.toString() && time[0] == changeData[i].time[0] && time[1] == changeData[i].time[1]) {
							switch(key){
								case 'execute':
									changeData[i].execute = true;
									break;
								case 'cancel':
									changeData[i].cancel = true;
									break;
							}
							break;
						}
					} 
					console.log(changeData)
					collection.update({day:day[0]+'-'+day[1]+'-'+day[2]}, {$set:{data:changeData}}, {safe:true}, function(err, result){
						if(err) {
							console.log('执行调度第四个err:'+err);	
							return;
						}
						console.log('已更新了执行标志');	
					});	
				});
			}
		});	
	},
	clearDaySch : function(day) {
		db.createCollection('schedule', {safe:true}, function(err, collection){
			if(err){
				console.log(err);
			}else{
				scheduleData = [];
				collection.update({day:day},{$set:{data:scheduleData}},{safe:true}, function(err, result){
					if(err) {
						console.log(err)	
					}
					else {
						console.log(result);
					}
				});
				return;	
			}
		});
	}
}
var manager = new Manager();
manager.init();
//每天晚上凌晨都重新读取新一天的计划。
var rule = new schedule.RecurrenceRule();
	rule.dayOfWeek = [0, new schedule.Range(1, 6)];
	rule.hour = 0;
　　rule.minute = 1;
　　var j = schedule.scheduleJob(rule, function(){
	 db.close(); 
　　　manager.init();
　　});
function inArray(arr, ele){
	if(0 == arr.length) return false;
	for(var i = 0, len = arr.length;i < len; i++) {
		if(ele == arr[i]) {
			return true;	
		}	
	}	
	return false;
}

function isEmptyObj(obj){
	for(var i in obj) {
		return false;	
	}
	return true;
}
function isArray(obj){
	if(undefined === obj) return false;
	if(obj.constructor == Array) {
		return true;	
	}
	return false;
}
//计算某个日期加天数得到的新日期
function getNewDay(dateTemp, days) { 
    var dateTemp = dateTemp.split("-");  
    var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]); //转换为MM-DD-YYYY格式    
    var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);  
    var rDate = new Date(millSeconds);  
    var year = rDate.getFullYear();  
    var month = rDate.getMonth() + 1;  
    if (month < 10) month =  month;  
    var date = rDate.getDate();  
    if (date < 10) date =  date;  
    return [year, month, date];  
}
//计算两个日期之间相差的天数
function  DateDiff(sDate1,  sDate2){     
   var  aDate,  oDate1,  oDate2,  iDays  
   aDate  =  sDate1.split("-")  
   oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])     
   aDate  =  sDate2.split("-")  
   oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  
   iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24)   
   return  iDays  
}    
//"2004/3/1 12:00"
function hourDiff(time1, time2) {
	var startDate= new Date(time1); 
	var endDate= new Date(time2); 
	var df=(endDate.getTime()-startDate.getTime()); 
	return df/1000/60/60;
}